package com.zf.shuashua.advert;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.widget.RemoteViews;

import androidx.core.content.FileProvider;

import com.zf.shuashua.BuildConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 广告apk下载类
 * todo：下载逻辑AsyncTask替换
 * 暂时不用
 * @deprecated
 */
public class DownloadManager {

    private RemoteViews mViews;
    private NotificationManager mNotifyMgr;
    private Notification mNotify;
    private int length;
    private Context mContext;
    private static final String UPGRADE_APK_PATH = Environment
            .getExternalStorageDirectory() + "/draw/advert.apk";

    private static DownloadManager instance;

    private DownloadManager() {

    }

    public static DownloadManager getInstance() {
        if (null == instance) {
            synchronized (DownloadManager.class) {
                if (null == instance) {
                    instance = new DownloadManager();
                }
            }
        }
        return instance;
    }

    public void loadFile(String url) {
        new LoadTask().execute(url);
    }


    private class LoadTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            showNotify();
        }

        protected String doInBackground(String... params) {
            FileOutputStream fos = null;
            InputStream is = null;
            try {
                URL url = new URL(params[0]);
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                // 设置超时时间
                conn.setConnectTimeout(25000);
                conn.setReadTimeout(25000);
                int responseCode = conn.getResponseCode();
                if (responseCode != HttpURLConnection.HTTP_OK) {
                    return null;
                }
                is = conn.getInputStream();
                int len = 0;
                byte[] buffer = new byte[1024];
                File upgradeFile = new File(UPGRADE_APK_PATH);
                if (!upgradeFile.exists()) {
                    // 如果文件不存在，说明是第一次升级，
                    // 需要先创建文件夹
                    upgradeFile.getParentFile().mkdirs();
                }
                fos = new FileOutputStream(UPGRADE_APK_PATH);
                int loaded = 0;// 已下载大小
                int times = 0;
                while (-1 != (len = is.read(buffer))) {
                    loaded += len;
                    fos.write(buffer, 0, len);
                    // 每下载8%更新一次通知
                    if (loaded * 100 / length >= 8 * times) {
                        times++;
                        publishProgress(loaded);
                    }
                }
                completeNotify();
            } catch (MalformedURLException e) {
            } catch (IOException e) {
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            updateNotify(values[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            finishNotify();
            Intent intent = new Intent(Intent.ACTION_VIEW);
            //判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileProvider", new File(UPGRADE_APK_PATH));
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(new File(UPGRADE_APK_PATH)), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            mContext.startActivity(intent);
        }

    }

    private void completeNotify() {
//		mViews.setProgressBar(R.id.progressBar1, 100, 100, false);
//		mViews.setTextViewText(R.id.textView1, 100 + "%");
//		mViews.setTextViewText(R.id.textView2, "已完成下载");
//		mNotifyMgr.notify(12345, mNotify);
    }

    private void updateNotify(int progress) {
//		int n = progress * 100 / length;
//		mViews.setProgressBar(R.id.progressBar1, length, progress, false);
//		mViews.setTextViewText(R.id.textView1, n + "%");
//		mViews.setTextViewText(R.id.textView2, "正在下载最新版本");
//		mNotifyMgr.notify(12345, mNotify);
    }

    private void finishNotify() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0,
                intent, 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileProvider", new File(UPGRADE_APK_PATH));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            intent.setDataAndType(Uri.fromFile(new File(UPGRADE_APK_PATH)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        mNotify.contentIntent = contentIntent;
        mNotify.flags = Notification.FLAG_AUTO_CANCEL;
        mNotifyMgr.notify(12345, mNotify);
    }

    private void showNotify() {
//		String channelId = "upgradeNotice";
//		mNotifyMgr = (NotificationManager) mContext
//				.getSystemService(Context.NOTIFICATION_SERVICE);
//		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
//			NotificationChannel notificationChannel = new NotificationChannel(channelId, "下载新版本", NotificationManager.IMPORTANCE_DEFAULT);
//			mNotifyMgr.createNotificationChannel(notificationChannel);
//		}
//		mViews = new RemoteViews(mContext.getPackageName(),
//				R.layout.custom_notification);
//		mNotify = new NotificationCompat.Builder(mContext, channelId)
//				.setSmallIcon(R.drawable.app_icon).setTicker("下载新版本")
//				.setWhen(System.currentTimeMillis()).setContent(mViews).build();
//		mNotify.flags = Notification.FLAG_NO_CLEAR;
//		mNotifyMgr.notify(12345, mNotify);
    }

}
